<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pay_index_module extends CI_Module {

    private   $data ;
    private   $wx_config ;
    public function __construct()
    {
        parent::__construct();
        $this->sid = $GLOBALS['sid'];
        $this->data =$GLOBALS['config'];
        $this->load->model('pay.pay_model');
        $this->load->model('order.Orderlog_model');
        $this->load->model('order.Orderinfo_model');
        $this->load->model('order.Orderpaylog_model');
        $this->load->model('order.Ordercontacts_model');
        $this->load->model('order.Orderticket_model');
        $this->load->model('order.Ordergodate_model');
        $this->load->model('order.Ordergoods_model');
        $this->load->model('order.Orderrent_model');
        $this->load->model('member.User_model');
        $this->load->model('weixin.weixin_model');
        $this->load->model('api.Java_Api_model');
        $this->wx_config = $this->weixin_model->db_get_setting();
    }

    public function index($order_id)
    {
        $session = $this->session->all_userdata();
        if ( ! empty($session['user_id']) && $session['is_login'] == '1')
        {

          $order_info = $this->order_info($order_id);
          $this->data = $order_info ;
          $must_money = $order_info['order_account'] - $order_info['paid_account'] ;
          if ( ! ($must_money > 0))
              $this->error('订单价格异常！', $order_info['redirect'], '1');
          if ($order_info['order_status'] == '1')
              $this->error('订单未审核',$order_info['redirect'],'1');
          if ($order_info['pay_status'] == '3')
              $this->error('订单已支付', $order_info['redirect'], '1');
          if ($order_info['cat_type'] == '1')
              $this->error('门市订单不允许支付', $order_info['redirect'], '1');
          $this->data['form_url'] = site_url('/payprocess');
          $this->data['must_money'] = $must_money;
          $this->data['order_id'] = $order_id;
          $this->load->view(TEMPLATE_NAME.'/view_pay', $this->data);
        }
        else
        {
            redirect(site_url('/denglu'));
        }
    }

    public function pay_process()
    {
        if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
        {
            $session = $this->session->all_userdata();
            $check_login = FALSE ;
            if(!empty($session['user_id'])&&$session['is_login']=='1')  $check_login = TRUE ;
            $param  = $this->input->get_post('Form');
            $order_id = $param['order_id'];
            $order_info = $this->order_info($order_id);
            $must_money = $order_info['order_account']-$order_info['paid_account'] ;
            $trade_no = $order_info['order_sn'] ;
            $desc = $order_info['order_title'] ;
            $total_fee = $must_money ;
            if(!($must_money>0)) $this->error('订单价格异常！',$order_info['redirect'],'1');
            if($order_info['order_status']=='1') $this->error('订单未审核',$order_info['redirect'],'1');
            if($order_info['pay_status']=='3') $this->error('订单已支付',$order_info['redirect'],'1');
            if($order_info['cat_type']=='1')   $this->error('门市订单不允许在线支付,登陆后台支付',$order_info['redirect'],'1');
            if($check_login)
            {
                if($param['pay']=='alipay')
                {
                    $this->pay_model->_alipay($trade_no,$desc,$total_fee,$body='',$order_info['goods_url'],$order_id);
                }

                if($param['pay']=='tenpay')
                {
                    $this->pay_model->_tenpay($trade_no,$desc,$total_fee,$order_id);
                }
                if($param['pay']=='cmcc')
                {
                    $array = array();
                    $time = date('Y-m-d H:i:s',time()) ;
                    $array['orderDate'] = substr(str_replace("-","",$time),0,8);
                    $array['orderTime'] = substr(str_replace(":","",$time),11,8);
                    $array['orderid'] =   $order_id;
                    $array['merURL'] =    site_url('pay/index/comm_return_url');
                    $array['goodsURL'] =  $order_info['goods_url'];
                    $array['amount'] =    $total_fee;
                    $array['orderContent'] =    $desc;
                    $array['payBatchNo'] =  substr($order_info['order_sn'],8);;
                    $array['redirect'] = $order_info['redirect'] ;
                    $this->comm_pay($array);
                }
                if ($param['pay'] == 'unionpay') {
                    $order_info['txnAmt'] = $must_money;
                    $order_info['order_id'] = $order_id;
                    $this->pay_model->_unionpay($order_info);
                }
                if ($param['pay'] == 'wxpay')
                {
                    $this->_wxpay($order_info);
                }
            }
            else
            {
                $this->error('支付异常',$order_info['redirect'] ,'1');
            }
        }
    }


    public function _wxpay($order_info)
    {
        $this->_wxpay_include_ini();
        $notify = new NativePay();
        $input = new WxPayUnifiedOrder();
        $input->SetBody($order_info['order_title']);
        $input->SetAttach($order_info['order_id']);
        $input->SetOut_trade_no($order_info['order_sn']. date("YmdHis"));
        $input->SetTotal_fee($order_info['order_account']*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($order_info['order_title']);
        $input->SetNotify_url(site_url('pay/index/wxpay_return_url'));
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($order_info['order_id']);
        $result = $notify->GetPayUrl($input);
        $return = $result['code_url'];
        $qrcode_img = '<img alt="模式一扫码支付" src="'.site_url('pay/index/wxpay_qrcode?data=').urlencode($return).'" />';
        $this->data = $order_info;
        $this->data['qrcode_img'] = $qrcode_img;
        $this->load->view(TEMPLATE_NAME.'/wxpay', $this->data);
     }

    public function wxpay_qrcode()
    {
        require_once FCPATH.'application/libraries/wxpay/lib/phpqrcode/phpqrcode.php';
        $url = urldecode($_GET["data"]);
        QRcode::png($url,$outfile = false, $level = QR_ECLEVEL_L, $size = 10, $margin = 2, $saveandprint=false);
    }

    public function wxpay_return_url()
    {
        $this->_wxpay_include_ini();
        $logHandler= new CLogFileHandler(APPPATH.'cache/wxp_logs/'.$this->sid.'/'.date('Y-m-d').'.log');
        Log::Init($logHandler, 15);
        Log::DEBUG("begin notify");
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
        $trade_data = $notify->data;
        $order_info = $this->order_info($trade_data["attach"]);
        Log::DEBUG("pay data".json_encode($order_info));
        if ($trade_data["return_code"] == "SUCCESS" && $trade_data["result_code"] == "SUCCESS")
        {
            if ($order_info['pay_status'] !== '3')
            {
                $this->_pay_finished($trade_data["attach"], $trade_data["total_fee"]);
            }
        }
    }

    private function _wxpay_include_ini()
    {
        define('WX_APPID', $this->wx_config['appid']);
        define('WX_APPSECRET', $this->wx_config['appsecret']);
        define('WX_MCHID', $GLOBALS['config']['mch_id']);
        define('WXPAY_KEY', $GLOBALS['config']['wxpay_key']);
        $wxpay_library = FCPATH . 'application/libraries/wxpay/lib/';
        require_once $wxpay_library . 'WxPay.Exception.php';
        require_once $wxpay_library . 'WxPay.Config.php';
        require_once $wxpay_library . 'WxPay.Data.php';
        require_once $wxpay_library . 'WxPay.Api.php';
        require_once $wxpay_library . 'WxPay.Notify.php';
        require_once $wxpay_library . 'WxPay.JsApiPay.php';
        require_once $wxpay_library . 'log.php';
        require_once $wxpay_library . 'PayNotifyCallBack.php';
        require_once $wxpay_library . 'WxPay.NativePay.php';
        dmkdir(APPPATH . 'cache/wxp_logs/' . $this->sid);
    }

    public function comm_pay($array)
    {
       /* $socket_ip = "61.147.75.105";
        $socket_port = "8080";
        $merID = $GLOBALS['config']['comm_account']; //商户号为固定
        $interfaceVersion = '1.0.0.0';
        $orderid =   $array['orderid'];
        $orderDate = $array['orderDate'];
        $orderTime = $array['orderTime'];
        $merURL =    $array['merURL'];
        $goodsURL =  $array['goodsURL'];
        $amount =    $array['amount'];
        $orderContent = $array['orderContent'];
        $payBatchNo = $array['payBatchNo']; //商品批次号
        $curType = 'CNY';
        $tranCode = "cb2200_sign";
        $tranType = '0';
        $notifyType = '1';
        $jumpSeconds = '3';
        $netType = '0';
        $orderMono = '';
        $phdFlag = '';
        $proxyMerName = '';
        $proxyMerType = '';
        $proxyMerCredentials = '';
        $issBankNo = '';
        $source = '';
        $merSignMsg = '';
        $source = "";*/

        //获得表单传过来的数据
        $socket_ip = "127.0.0.1";
        $socket_port = "8080";
         //$merchID = $GLOBALS['config']['comm_account']; //商户号为固定
        $merchID = '301310063009501'; //商户号为固定
        $interfaceVersion = '1.0.0.0';
        $merID = $merchID; //商户号为固定
        $orderid   = $array['orderid'];
        $orderDate = $array["orderDate"];
        $orderTime = $array["orderTime"];
        $goodsURL  = $array["goodsURL"];
        $amount    = $array["amount"];
        $orderContent = $array["orderContent"];
        $payBatchNo = $array["payBatchNo"];
        $curType = 'CNY';
        $orderMono = '备注';
        $tranType = '0';
        $phdFlag = '';
        $notifyType = '1';
        $netType = '0';
        $tranCode = "cb2200_sign";
        $merURL = '';
        $jumpSeconds = '3';
        $proxyMerName = '';
        $proxyMerType = '';
        $proxyMerCredentials = '';
        $issBankNo = '';
        $source = "";
         //连接字符串
        $source = $interfaceVersion."|".$merID."|".$orderid."|".$orderDate."|".$orderTime."|".$tranType."|"
            .$amount."|".$curType."|".$orderContent."|".$orderMono."|".$phdFlag."|".$notifyType."|".$merURL."|"
            .$goodsURL."|".$jumpSeconds."|".$payBatchNo."|".$proxyMerName."|".$proxyMerType."|".$proxyMerCredentials."|".$netType;


        //连接地址
        $socketUrl = "tcp://".$socket_ip.":".$socket_port;
        $fp = stream_socket_client($socketUrl, $errno, $errstr, 30);
        $retMsg="";

        if(!$fp)
        {
            echo "$errstr ($errno)<br />\n";
        }
        else
        {
            $in  = "<?xml version='1.0' encoding='UTF-8'?>";
            $in .= "<Message>";
            $in .= "<TranCode>".$tranCode."</TranCode>";
            $in .= "<MsgContent>".$source."</MsgContent>";
            $in .= "</Message>";
            fwrite($fp, $in);
            while (!feof($fp)) {
                $retMsg =$retMsg.fgets($fp, 1024);
            }
            fclose($fp);
        }
        echo "retMsg=".$retMsg."***************";

        //解析返回xml
        $dom = new DOMDocument;
        $dom->loadXML($retMsg);

        $retCode = $dom->getElementsByTagName('retCode');
        $retCode_value = $retCode->item(0)->nodeValue;

        $errMsg = $dom->getElementsByTagName('errMsg');
        $errMsg_value = $errMsg->item(0)->nodeValue;

        $signMsg = $dom->getElementsByTagName('signMsg');
        $signMsg_value = $signMsg->item(0)->nodeValue;

        $orderUrl = $dom->getElementsByTagName('orderUrl');
        $orderUrl_value = $orderUrl->item(0)->nodeValue;
        echo "retMsg=".$retMsg;
        echo $retCode_value." ".$errMsg_value." ".$signMsg_value." ".$orderUrl_value;

        if($retCode_value != "0")
        {
            echo "交易返回码：".$retCode_value."<br>";
            echo "交易错误信息：" .$errMsg_value."<br>";
        }
        else
        {
            $this->data['orderUrl_value'] = $orderUrl_value;
            $this->data['amount'] = $amount;
            $this->data['orderContent'] = $orderContent;
            $this->data['merID'] = $merID;
            $this->data['orderid'] = $orderid;
            $this->data['orderDate'] = $orderDate;
            $this->data['orderTime'] = $orderTime;
            $this->data['tranType'] = $tranType;
            $this->data['amount'] = $amount;
            $this->data['curType'] = $curType;
            $this->data['orderContent'] = $orderContent;
            $this->data['orderMono'] = $orderMono;
            $this->data['phdFlag'] = $phdFlag;
            $this->data['notifyType'] = $notifyType;
            $this->data['merURL'] = $merURL;
            $this->data['goodsURL'] = $goodsURL;
            $this->data['jumpSeconds'] = $jumpSeconds;
            $this->data['payBatchNo'] = $payBatchNo;
            $this->data['proxyMerName'] = $proxyMerName;
            $this->data['proxyMerType'] = $proxyMerType;
            $this->data['proxyMerCredentials'] = $proxyMerCredentials;
            $this->data['netType'] = $netType;
            $this->data['signMsg_value'] = $signMsg_value;
            $this->data['redirect'] = $array['redirect'];
            $this->load->view(TEMPLATE_NAME.'/comm_pay',$this->data);
        }

    }



    public function tenpay_return_url()
    {
        $order_id = $this->uri->segment(4);
        $this->load->library('tenpay/PayResponseHandler');
        $key = $GLOBALS['config']['tenpay_key'];
        $resHandler = new PayResponseHandler();
        $resHandler->setKey($key);
        $order_info = $this->order_info($order_id);
        if($resHandler->isTenpaySign()){
            $sp_billno = $resHandler->getParameter("sp_billno");              //商家订单号
            $transaction_id = $resHandler->getParameter("transaction_id");    //财付通交易单号
            $total_fee = $resHandler->getParameter("total_fee");              //金额,以分为单位
            $pay_result = $resHandler->getParameter("pay_result");            //支付结果
            if( "0" == $pay_result)
            {
                    if($order_info['pay_status']!=='3')
                    {
                        if($this->_pay_finished($order_id,$total_fee))
                        {
                            $this->success('支付成功',$order_info['redirect'],'1');
                        }
                    }
                    else
                    {
                        $this->success('订单已支付',$order_info['redirect'],'1');
                    }
            }
        }
        else
        {
            $this->error('支付失败',$order_info['redirect'],'1');
        }

    }

    public function comm_return_url()
    {
        $notifyMsg=$_REQUEST;
        $abc = array_shift($notifyMsg);
        $result= explode("|",$abc);
        if($result[9] = 1)
        {
            echo  "交易成功";
        }
        else{
            echo "交易失败";
        }

    }
    public function alipay_return_url()
    {
        $order_id = $this->uri->segment(4);
        $out_trade_no = $this->input->get_post('out_trade_no');   //商户订单号
        $trade_no = $this->input->get_post('trade_no');           //支付宝交易号
        $trade_status = $this->input->get_post('trade_status');   //交易状态
        $total_fee = $this->input->get_post('total_fee');         //交易金额
        $order_info = $this->order_info($order_id);
        if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS')
        {
            if($order_info['pay_status']!=='3')
            {
                if($this->_pay_finished($order_id,$total_fee))
                {
                    $this->success('支付成功',$order_info['redirect'],'1');
                }
            }
            else
            {
                $this->success('订单已支付',$order_info['redirect'],'1');
            }
        }
        else
        {
            $this->error('支付失败',$order_info['redirect'],'1');
        }
    }

    public function unionpay_return_url() {
        $this->load->library('unionpay/UnionPay');
        $order_id = $this->uri->segment(4);
        $total_fee = $this->input->get_post('txnAmt')/100;
        $order_info = $this->order_info($order_id);
        // 生产环境从数据库讯取
        $unionpay_verify_cert_path = BASEPATH . $GLOBALS['config']['unionpay_public_verify_cert'];
        $unionpay = new Unionpay();
        $result = $unionpay->receive($_POST, $unionpay_verify_cert_path);

        if ($result) {
            if($order_info['pay_status']!=='3')
            {
                if ($this->_pay_finished($order_id, $total_fee))
                {
                    $this->success('支付成功', $order_info['redirect'], '1');
                }
                else
                {
                    log_message('error', '银联支付失败');
                }
            }
            else
            {
                $this->success('订单已支付', $order_info['redirect'], '1');
            }
            // $orderId = $_POST ['orderId']; //其他字段也可用类似方式获取
        }
        else {
            log_message('error','银联支付认证失败 '.ParamsToString($_POST));
        }
    }

    public function _pay_finished($order_id,$total_fee)
    {

        $pay_data = array(
            'order_id' => $order_id,
            'order_status' => '2',
            'user_type' => '2',
        );

        $pay_res = $this->Orderinfo_model->translate_order_status($pay_data);

        $log_data = array(
            'pay_account' => $total_fee,
            'order_id' => $order_id,
            'order_status ' => '2',
            'user_type' => '2',
            'status' => '2',
            'type' => '1'
        );
        $log_res = $this->Orderpaylog_model->save_pay_account($log_data);
        if ($pay_res && $log_res)
        {
            $return = $this->order_info($order_id);
            if ($return['order_type'] == '1' && isset($return['api_order_sn']) && $return['api_order_sn'] > 0)
            {
                $this->Java_Api_model->order_pay_interface($return['api_order_sn'],$total_fee ,$this->session->userdata('mobile'), $order_id);
            }
            $this->User_model->_send_sms($return['mobile'], $return['template']);
            return true;
        }
    }

    public function check_pay_status()
    {
        $order_id = intval($this->input->get_post('order_id'));
        $order_info = $this->Orderinfo_model->get_row(array('order_id'=>$order_id));
        if($order_info['pay_status'] == '3')
        {
            echo json_encode(array('status'=>1, 'msg'=>'success'));
        }
        else
        {
            echo json_encode(array('status'=>-1, 'msg'=>'fail'));
        }
    }

    public function order_info($order_id)
    {
        $return = array() ;
        $order_info = $this->Orderinfo_model->get_row(array('order_id'=>$order_id));
        $contacts_info = $this->Ordercontacts_model->get_row(array('order_id'=>$order_id));
        if($order_info['order_type'] == '1')
        {
            $template = $this->data['line_order_template_pay'];
            $order_detail =  $this->Ordergodate_model->get_row(array('order_id'=>$order_id));
            $return['order_sn'] = $order_info['order_sn'];
            $return['order_title'] = $order_detail['line_name'];
            $return['order_date'] =  $order_detail['go_date'];
            $return['order_num'] =  $order_detail['total_num'].'人';
            $return['order_type'] = $order_info['order_type'] ;
            $return['cat_type'] = $order_info['cat_type'] ;
            $return['order_status'] = $order_info['order_status'] ;
            $return['mobile'] = $contacts_info['phone_num'] ;
            $return['pay_status'] = $order_info['pay_status'] ;
            $return['order_account'] = $order_info['order_account'] ;
            $return['paid_account'] = $order_info['paid_account'] ;
            $return['redirect'] = site_url('order/index/line_info?id='.$order_id);
            $return['goods_url'] = site_url("xianlu/{$order_detail['line_id']}.html");
            $return['add_time'] = $order_info['add_time'] ;
            $return['api_order_sn'] = $order_info['api_order_sn'] ;
            $return['order_id'] = $order_id ;
            $target = array(
                '{$order_sn}',
                '{$order_account}',
                '{$line_name}',
                '{$go_date}',
                '{$contact_name}',
                '{$contact_phone}',
                '{$order_account}'
            );
            $replace = array(
                $order_info['order_sn'],
                $order_detail['order_account'],
                $order_detail['line_name'],
                $order_detail['go_date'],
                $contacts_info['name'],
                $contacts_info['phone_num'],
                $return['order_account']
            );
            $return['template'] = str_replace($target,$replace,$template);
        }

        if($order_info['order_type']=='2')
        {
            $template =  $this->data['ticket_order_template_pay'];
            $table = $this->db->dbprefix("order_tickets");
            $order_detail = $this->Orderticket_model->get_row(array($table.'.order_id'=>$order_id));
            $return['order_sn'] = $order_info['order_sn'];
            $return['order_title'] = $order_detail['scenic_name'].$order_detail['name'];
            $return['order_date'] =  $order_detail['user_date'];
            $return['order_num'] =  $order_detail['num'].'张';
            $return['order_type'] = $order_info['order_type'] ;
            $return['cat_type'] = $order_info['cat_type'] ;
            $return['order_status'] = $order_info['order_status'] ;
            $return['mobile'] = $contacts_info['phone_num'] ;
            $return['pay_status'] = $order_info['pay_status'] ;
            $return['order_account'] = $order_info['order_account'] ;
            $return['paid_account'] = $order_info['paid_account'] ;
            $return['redirect'] = site_url('order/index/ticket_info?id='.$order_id);
            $return['goods_url'] = site_url("jingdian/{$order_detail['scenic']}.html");
            $return['add_time'] = $order_info['add_time'] ;
            $return['order_id'] = $order_id ;
            $target = array(
                '{$order_sn}',
                '{$order_account}',
                '{$scenic_name}',
                '{$ticket_name}',
                '{$user_date}',
                '{$num}',
                '{$contact_phone}',
                '{$order_account}'
            );
            $replace = array(
                $order_info['order_sn'],
                $order_info['order_account'],
                $order_detail['scenic_name'],
                $order_detail['name'],
                $order_detail['user_date'],
                $order_detail['num'],
                $contacts_info['phone_num'],
                $return['order_account']
            );
            $return['template'] = str_replace($target,$replace,$template);
        }

        if($order_info['order_type']=='3')
        {
            $template =  $this->data['goods_order_template_pay'];
            $table = $this->db->dbprefix("order_goods");
            $order_detail = $this->Ordergoods_model->get_row(array($table.'.order_id'=>$order_id));
            $return['order_sn'] = $order_info['order_sn'];
            $return['order_title'] = $order_detail['goods_name'];
            $return['order_num'] =  $order_detail['num'].'个';
            $return['order_type'] = $order_info['order_type'] ;
            $return['cat_type'] = $order_info['cat_type'] ;
            $return['order_status'] = $order_info['order_status'] ;
            $return['mobile'] = $contacts_info['phone_num'] ;
            $return['pay_status'] = $order_info['pay_status'] ;
            $return['order_account'] = $order_info['order_account'] ;
            $return['paid_account'] = $order_info['paid_account'] ;
            $return['redirect'] = site_url('order/index/goods_info?id='.$order_id);
            $return['goods_url'] = site_url("goods/.html");
            $return['add_time'] = $order_info['add_time'] ;
            $return['order_id'] = $order_id ;
            $target = array(
                '{$order_sn}',
                '{$order_account}',
                '{$goods_name}',
                '{$num}',
                '{$contact_phone}',
                '{$order_account}'
            );
            $replace = array(
                $order_info['order_sn'],
                $order_info['order_account'],
                $order_detail['goods_name'],
                $order_detail['num'],
                $contacts_info['phone_num'],
                $return['order_account']
            );
            $return['template'] = str_replace($target,$replace,$template);
        }

        if($order_info['order_type']=='5')
        {
            $order_detail = $this->Orderrent_model->get_row(array('order_id'=>$order_id));
            $return['order_date'] =  $order_detail['go_date'];
            $return['order_sn'] = $order_info['order_sn'];
            $return['order_title'] = '租车订单';
            $return['order_num'] =  $order_info['order_note'];
            $return['order_type'] = $order_info['order_type'] ;
            $return['cat_type'] = $order_info['cat_type'] ;
            $return['order_status'] = $order_info['order_status'] ;
            $return['mobile'] = $contacts_info['phone_num'] ;
            $return['pay_status'] = $order_info['pay_status'] ;
            $return['order_account'] = $order_info['order_account'] ;
            $return['paid_account'] = $order_info['paid_account'] ;
            $return['redirect'] = site_url('order/index/rent_info?id='.$order_id);
            $return['goods_url'] = site_url("zuche");
            $return['add_time'] = $order_info['add_time'] ;
            $return['order_id'] = $order_id ;
            /*$target = array(
                '{$order_sn}',
                '{$order_account}',
                '{$goods_name}',
                '{$num}',
                '{$contact_phone}',
                '{$order_account}'
            );
            $replace = array(
                $order_info['order_sn'],
                $order_info['order_account'],
                $order_detail['goods_name'],
                $order_detail['num'],
                $contacts_info['phone_num'],
                $return['order_account']
            );
            $return['template'] = str_replace($target,$replace,$template);*/
        }
        return $return ;
    }

}
